package com.worldtvs.online.view;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.worldtv.lives.R;
import com.worldtvs.online.E4KidsConfig;
import com.worldtvs.online.E4KidsSlidingMenuActivity;
import com.worldtvs.online.adapter.DetailVideoPagerAdapter;
import com.worldtvs.online.fragment.IndexFragment;
import com.worldtvs.online.fragment.IndexNewFreagment;
import com.worldtvs.online.fragment.IndexViewFragment;
import com.worldtvs.online.util.Debug;
import com.worldtvs.online.util.TabFactory;

public class IndexActivity extends E4KidsSlidingMenuActivity implements
	OnTabChangeListener, OnPageChangeListener, OnClickListener {
    private TabHost mTabHost;
    private ViewPager pager;

    private ImageView ivABCancelSearch;
    private ImageView ivABSearch;
    private EditText edtABSearch;
    private LinearLayout llContainEdt;
    private ImageView tvABTitle;
    private ImageView ivABLogo;
    private AdView adView;
	private InterstitialAd interstitial;
	RelativeLayout rlContainAds;
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.layout_index);

	this.setBehindContentView(R.layout.frame_layout_container);
	// this.getSlidingMenu().setSecondaryMenu(R.layout.frame_right_container);
	this.setDefaultBar();
	configLeftSlideMenu();
	// this.removeSlidingMenu();

	init();

	List<Fragment> listFragments = new ArrayList<Fragment>();

	listFragments.add(new IndexFragment());
	listFragments.add(new IndexNewFreagment());
	listFragments.add(new IndexViewFragment());

	DetailVideoPagerAdapter adapter = new DetailVideoPagerAdapter(
		IndexActivity.this, getSupportFragmentManager(), listFragments);

	pager.setAdapter(adapter);
	pager.setOffscreenPageLimit(2);
	pager.setOnPageChangeListener(this);

    }

    private void init() {

	
	ivABCancelSearch = actionBar.getIvABCancelSearch();
	ivABSearch = actionBar.getIvABSearch();
	edtABSearch = actionBar.getEdtABSearch();
	llContainEdt = actionBar.getLlContainEdt();
	ivABLogo = actionBar.getIvABLogo();
	tvABTitle = actionBar.getIvTitle();
	
	ivABLogo.setOnClickListener(new OnClickListener() {
	    
	    @Override
	    public void onClick(View arg0) {
		toggle();
	    }
	});

	// edtABSearch.setOnEditorActionListener(searchAction);
	ivABSearch.setOnClickListener(this);
	ivABCancelSearch.setOnClickListener(this);

	edtABSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
	edtABSearch.setOnEditorActionListener(new OnEditorActionListener() {

	    @Override
	    public boolean onEditorAction(TextView arg0, int actionID,
		    KeyEvent arg2) {
		// RequestUrlService.requestSearchNameSinger(delegateSinger,
		// "tuan hung");
		String text = edtABSearch.getText().toString().trim();
		if (!text.equals("") || !TextUtils.isEmpty(text)) {
		   
		    goActivitySearch(IndexActivity.this,SearchResultActivity.class, E4KidsConfig.KEY_INTENT_SEARCH, text);
		}
		return true;
	    }
	});

	mTabHost = (TabHost) findViewById(android.R.id.tabhost);
	mTabHost.setOnTabChangedListener(this);
	pager = (ViewPager) findViewById(R.id.cate_info_pager);

	mTabHost.setup();
	addTab();
    }

    private void addTab() {
	View tabIndicator = LayoutInflater.from(IndexActivity.this).inflate(
		R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
	View tabIndicator1 = LayoutInflater.from(IndexActivity.this).inflate(
		R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
	View tabIndicator2 = LayoutInflater.from(IndexActivity.this).inflate(
		R.layout.tab_tabhost, mTabHost.getTabWidget(), false);
	TextView tvNew = (TextView) tabIndicator.findViewById(R.id.title);
	TextView tvIndex = (TextView) tabIndicator1.findViewById(R.id.title);
	TextView tvlike = (TextView) tabIndicator2.findViewById(R.id.title);

	tvNew.setText(getString(R.string.index_v_new));
	tvIndex.setText(getString(R.string.index_));
	tvlike.setText(getString(R.string.index_most_view));

	TabHost.TabSpec tSpecIndex = mTabHost.newTabSpec(getString(R.string.index_));
	tSpecIndex.setIndicator(tabIndicator1);
	tSpecIndex.setContent(new TabFactory(IndexActivity.this));
	mTabHost.addTab(tSpecIndex);

	TabHost.TabSpec tSpecNew = mTabHost.newTabSpec(getString(R.string.index_v_new));
	tSpecNew.setIndicator(tabIndicator);

	tSpecNew.setContent(new TabFactory(IndexActivity.this));
	mTabHost.addTab(tSpecNew);

	TabHost.TabSpec tSpecLike = mTabHost.newTabSpec(getString(R.string.index_most_view));
	tSpecLike.setIndicator(tabIndicator2);
	tSpecLike.setContent(new TabFactory(IndexActivity.this));
	mTabHost.addTab(tSpecLike);

    }

    @Override
    public void onTabChanged(String arg0) {
	int pos = this.mTabHost.getCurrentTab();
	this.pager.setCurrentItem(pos);
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageSelected(int arg0) {
	if (arg0 == 0) {
	    enableSlidingMenu();
	} else {
	    this.removeSlidingMenu();
	}
	this.mTabHost.setCurrentTab(arg0);
    }

    private void showDialog() {

	if (dialog == null) {
	    dialog = new Dialog(IndexActivity.this);
	    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}

	dialog.setCancelable(true);
	dialog.setCanceledOnTouchOutside(false);
	dialog.setContentView(R.layout.layout_exit);

	Button btLeft = (Button) dialog.findViewById(R.id.btExitLeft);
	Button btRight = (Button) dialog.findViewById(R.id.btExitRight);
	Button btCenter = (Button) dialog.findViewById(R.id.btExitCenter);
	Button btIntentApp = (Button) dialog.findViewById(R.id.btIntentApp);
//	Button btDownload = (Button) dialog.findViewById(R.id.btDownload);
//	Button btSkip = (Button) dialog.findViewById(R.id.btSkip);
	final LinearLayout llLstAds = (LinearLayout) dialog
		.findViewById(R.id.llAds);
	JSONArray jArrLstAds = app.getjArrAdsExit();
	int lengthAds = jArrLstAds.length();
	for (int i = 0; i < lengthAds; i++) {
	    try {
	    JSONObject jObjDetailAds = jArrLstAds.getJSONObject(i);
	    
	    LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    View vAds = mInflater.inflate(R.layout.layout_banner_my_ads, null);
	    
	    ImageView ivAvatar = (ImageView)vAds.findViewById(R.id.ivAds);
	    TextView tvNameAds = (TextView)vAds.findViewById(R.id.tvNameAds);
	    TextView tvContentAds = (TextView)vAds.findViewById(R.id.tvContentAds);
	    final LinearLayout llMyads = (LinearLayout)vAds.findViewById(R.id.llMyads);
	    
	    Button btDownloadAds = (Button)vAds.findViewById(R.id.btDownload);
	    Button btSkip = (Button)vAds.findViewById(R.id.btSkip);
	    
	    
	    String linkImage = jObjDetailAds.getString("image");
	    String name = jObjDetailAds.getString("title");
	    String content = jObjDetailAds.getString("content");
	    final String linkMarket = jObjDetailAds.getString("link");
	    
	    tvNameAds.setText(name);
	    tvContentAds.setText(content);
	    
	    imageLoader.displayImage(linkImage, ivAvatar, options);
	    
	    btDownloadAds.setOnClickListener(new OnClickListener() {
	        
	        @Override
	        public void onClick(View v) {

			String packageName = linkMarket;
			try {
			    StringBuilder strb = new StringBuilder();
			    strb.append("market://details?id=").append(
				    packageName);
			    Debug.debug("Market : " + strb.toString());

			    Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.setData(Uri.parse(strb.toString()));
			    startActivity(intent);
			} catch (ActivityNotFoundException activityNotFound) {
			    // to handle play store not installed scenario
			    Intent intent = new Intent(
				    Intent.ACTION_VIEW,
				    Uri.parse("http://play.google.com/store/apps/details?id="
					    + packageName));
			    startActivity(intent);
			}
		    
	        }
	    });
	    
	    btSkip.setOnClickListener(new OnClickListener() {
	        
	        @Override
	        public void onClick(View v) {
	    		llMyads.setVisibility(View.GONE);
	        }
	    });
	    
	    llLstAds.addView(vAds, i);
	    } catch (JSONException e) {
		e.printStackTrace();
	    }
	}

	dialog.setOnCancelListener(new OnCancelListener() {

	    @Override
	    public void onCancel(DialogInterface arg0) {
		
	    }
	});

	btRight.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {
		
	    }
	});
	
	btIntentApp.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {
		try {
		    StringBuilder strb = new StringBuilder();
		    strb.append("market://search?q=pub:globaledu");
		    Debug.debug("Market : " + strb.toString());

		    Intent intent = new Intent(Intent.ACTION_VIEW);
		    intent.setData(Uri.parse(strb.toString()));
		    startActivity(intent);
		} catch (ActivityNotFoundException activityNotFound) {
		    // to handle play store not installed scenario
		    Intent intent = new Intent(
			    Intent.ACTION_VIEW,
			    Uri.parse("http://play.google.com/store/search?q=pub:globaledu"));
		    startActivity(intent);
		}

	    }
	});

	btLeft.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {
		
		hidenDialog();
//		onBackPressed();
		IndexActivity.this.finish();
	    }
	});

	btCenter.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		runOnUiThread(new Runnable() {

		    @Override
		    public void run() {
			String packageName = getApplicationContext()
				.getPackageName();
			try {
			    StringBuilder strb = new StringBuilder();
			    strb.append("market://details?id=").append(
				    packageName);
			    Debug.debug("Market : " + strb.toString());

			    Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.setData(Uri.parse(strb.toString()));
			    startActivity(intent);
			} catch (ActivityNotFoundException activityNotFound) {
			    // to handle play store not installed scenario
			    Intent intent = new Intent(
				    Intent.ACTION_VIEW,
				    Uri.parse("http://play.google.com/store/apps/details?id="
					    + packageName));
			    startActivity(intent);
			}
		    }
		});
	    }
	});

	dialog.show();
    }

    private void hidenDialog() {
	if (dialog != null) {
	    dialog.dismiss();
	    dialog = null;
	}
    }


    @Override
    public void onClick(View arg0) {
	switch (arg0.getId()) {
	case R.id.iv_search:
	    if (llContainEdt.getVisibility() == View.GONE) {
		llContainEdt.setVisibility(View.VISIBLE);
		ivABSearch.setVisibility(View.GONE);
		tvABTitle.setVisibility(View.GONE);
		edtABSearch.setFocusable(true);
		edtABSearch.requestFocus();
		showBoard(edtABSearch);
	    }
	    break;
	case R.id.iv_cancel:
	    String text = edtABSearch.getText().toString().trim();
	    if (!text.equals("")) {
		edtABSearch.setText("");
	    } else {
		llContainEdt.setVisibility(View.GONE);
		ivABSearch.setVisibility(View.VISIBLE);
		tvABTitle.setVisibility(View.VISIBLE);
		edtABSearch.setFocusable(true);
		hiddenBoard(edtABSearch);
	    }
	    break;
	}
	
    }
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        toggle();
        finish();
    }
}
